package com.zynn.service.module.recommend.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.zynn.common.core.utils.JsonUtil;
import com.zynn.service.module.recommend.BO.DiscoveryBO;
import com.zynn.service.module.recommend.BO.UserFriendEsBO;
import com.zynn.service.module.recommend.entity.SchoolFriendWithWeight;
import com.zynn.service.module.recommend.dao.RecommendMapper;
import com.zynn.service.module.recommend.service.RecommendService;
import net.minidev.json.JSONUtil;
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.RandomScoreFunctionBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Stream;


/**
 * @author jerry-liqi
 *
 * <p>
 *  推荐好友查询信息
 * </p>
 *
 */
@Service
public class RecommendServiceImpl extends ServiceImpl<RecommendMapper,SchoolFriendWithWeight> implements RecommendService {


    @Autowired
    private RestHighLevelClient client;



    /** class Result */
    private static class Result {


        /** return List<SchoolFriendWithWeight>
         *  查询同校推荐好友
         */
        public static List<SchoolFriendWithWeight> schoolFriendList(RestHighLevelClient client, SearchSourceBuilder builder) {

            SearchRequest request = new SearchRequest();
            request.source(builder);
            request.indices("user_friend_index");

            List<SchoolFriendWithWeight> result = new ArrayList<>();

            try {
                SearchResponse response = client.search(request);

                SearchHit[] hits = response.getHits().getHits();


                Stream<SearchHit> stream = Arrays.stream(hits);

                stream.forEach(hit -> System.out.println(hit.getSourceAsMap()));
            } catch(Exception e) {

            }
            return result;
        }

    }


    /**
     * @author jerry-liqi
     * @param userId 用户ID
     * @return
     */
    @Override
    public List<SchoolFriendWithWeight> getRecommendSchoolFriends(Long userId) {
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.constantScoreQuery(QueryBuilders.termsQuery("user_id", Arrays.asList(10231739))));

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 组装
        searchSourceBuilder.query(QueryBuilders.functionScoreQuery(builder, new RandomScoreFunctionBuilder()));

        // 执行
        Result.schoolFriendList(client,searchSourceBuilder);
        return null;
    }


    @Override
    public Map<String, Object> recommendSchoolV2(Long userId, Long gradeId, Long departmentId, Integer sex, Integer pageIndex) {
        Map<String,Object> result = Maps.newHashMap();


        this.getSameSchool(userId,gradeId,departmentId,sex,pageIndex,20);


        return null;
    }

    /**
     * 获取同校好友 分页查询
     *
     * @return map
     */
    private Map<String,Object> getSameSchool(Long userId,Long gradeId,Long departmentId,Integer sex,Integer pageNum,Integer pageSize){
        Map<String,Object> result = Maps.newHashMap();
        DiscoveryBO discoveryBO = new DiscoveryBO();

        // 一页显示几条
        pageSize = Objects.isNull(pageSize) ? 10 :pageSize;

        // 起始页码

        this.getSchoolFriendFromEs(userId,gradeId,departmentId,sex,discoveryBO);




        return null;
    }

    /**
     * 从ES分页获取  同校推荐用户 李琦
     *
     */
    private Set<Long> getSchoolFriendFromEs(Long userId, Long gradeId, Long departmentId, Integer sex, DiscoveryBO discoveryBO){

        // 开始时间
        Long sTime = System.currentTimeMillis();

        // 排除用户不想看到的好友
        Set<Long> set = new HashSet<>();
        set.add(1459177L);

        if (CollectionUtils.isEmpty(discoveryBO.getBlockIds())){
            discoveryBO.setBlockIds(set);
        } else {
            discoveryBO.getBlockIds().addAll(set);
        }

        UserFriendEsBO friendEsBO = this.getUserFriendFromES(userId);

        Long eTime = System.currentTimeMillis();

        System.out.println("打印时间"+(eTime-sTime));

        return null;
    }


    /**
     * 从es中获取
     */
    private UserFriendEsBO getUserFriendFromES(Long userId){

        GetRequest request = new GetRequest("user_friend_index","_doc",userId.toString());

        try {
            GetResponse response = client.get(request);

            UserFriendEsBO friendEsBO = (UserFriendEsBO)JsonUtil.json2object(response.getSourceAsString(),UserFriendEsBO.class);

            JSONObject jsonObject = JSONObject.parseObject(friendEsBO.getBlend_school_user_friend_with_weight().get(0));
            System.out.println(jsonObject);

            return friendEsBO;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
